/**
 * @file sle_client.c
 * @brief SLE Client implementation for device discovery and connection management.
 *
 * This file contains the implementation of the SLE client, which is responsible for
 * discovering devices, managing connections, and handling communication with remote devices.
 *
 * @author Maker Studio
 * @license Apache 2.0
 *
 * This code is open-sourced under the Apache 2.0 license. When using open-source libraries
 * or code, please ensure to acknowledge the original authors and sources.
 */

#include <stdio.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "iot_pwm.h"

#define PWM_GPIO IOT_IO_NAME_GPIO_9
#define PWM_PORT 1

static const uint16_t g_tuneFreqs[] = {
    0,
    1046,
    1174,
    1318,
    1397,
    1568,
    1760,
    1975,
    784
};

static const uint8_t g_scoreNotes[] = {
    1, 2, 3, 1,        1, 2, 3, 1,        3, 4, 5,  3, 4, 5,
    5, 6, 5, 4, 3, 1,  5, 6, 5, 4, 3, 1,  1, 8, 1,  1, 8, 1,
};

static const uint8_t g_scoreDurations[] = {
    4, 4, 4, 4,        4, 4, 4, 4,        4, 4, 8,  4, 4, 8,
    3, 1, 3, 1, 4, 4,  3, 1, 3, 1, 4, 4,  4, 4, 8,  4, 4, 8,
};

/**
 * @brief Task to play music using PWM.
 *
 * This task plays a sequence of notes using PWM to generate sound.
 *
 * @param arg Unused parameter.
 */
static void BeeperMusicTask(void *arg)
{
    (void)arg;

    printf("BeeperMusicTask start!\r\n");

    for (size_t i = 0; i < sizeof(g_scoreNotes)/sizeof(g_scoreNotes[0]); i++) {
        uint32_t tune = g_scoreNotes[i];
        uint16_t freq = g_tuneFreqs[tune];
        uint32_t tuneInterval = g_scoreDurations[i] * (125*1000);
        printf("%d %d %d\r\n", tune, freq, tuneInterval);
        IoTPwmStart(PWM_PORT, 50, freq*6);
        usleep(tuneInterval);
        IoTPwmStop(PWM_PORT);
        usleep(20*1000);
    }
}

/**
 * @brief Initialize and start the BeeperMusicTask.
 *
 * This function creates a new thread to run the BeeperMusicTask.
 */
static void StartBeepMusicTask(void)
{
    osThreadAttr_t attr;
    attr.name = "BeeperMusicTask";
    attr.stack_size = 1024 * 10;
    attr.priority = osPriorityNormal;

    IoTGpioInit(PWM_GPIO);
    IoSetFunc(PWM_GPIO, IOT_IO_FUNC_GPIO_9_PWM1_OUT);
    IoTGpioSetDir(PWM_GPIO, IOT_GPIO_DIR_OUT);
    IoTPwmInit(PWM_PORT);

    if (osThreadNew(BeeperMusicTask, NULL, &attr) == NULL) {
        printf("[BeeperMusicExample] Falied to create BeeperMusicTask!\n");
    }
}

SYS_RUN(StartBeepMusicTask);